/*
 * CVideoDecoder.cpp
 *
 *  Created on: 2018年5月21日
 *      Author: zhengboyuan
 */

#include "CVideoDecoder.h"

namespace av
{

CVideoDecoder::CVideoDecoder():
		m_codecCtx()
{
}

CVideoDecoder::~CVideoDecoder()
{
	close();
}

int CVideoDecoder::open(const MediaFormat& fmt)
{
	AVCodec* pCodec = avcodec_find_decoder((AVCodecID)fmt.m_codec);
	if (!pCodec)
	{
		return EBADF;
	}

	m_codecCtx = avcodec_alloc_context3(pCodec);

	m_codecCtx->refcounted_frames = 1;
	m_codecCtx->codec_type = AVMEDIA_TYPE_VIDEO;

	if (fmt.m_videoProp.size())
	{
		m_codecCtx->extradata = (uint8_t*)av_memdup(fmt.m_videoProp.c_str(), fmt.m_videoProp.size());
		m_codecCtx->extradata_size = fmt.m_videoProp.size();
	}

	if (avcodec_open2(m_codecCtx, pCodec, NULL) < 0)
	{
		avcodec_close(m_codecCtx);
		av_free(m_codecCtx);
		m_codecCtx = NULL;
		return EBADF;
	}


	return 0;
}

void CVideoDecoder::close()
{
	if (m_codecCtx)
	{
		avcodec_close(m_codecCtx);
		av_free(m_codecCtx);
		m_codecCtx = NULL;
	}
}

bool CVideoDecoder::isOpen()
{
	return (m_codecCtx != NULL);
}

bool CVideoDecoder::decode(AVPacketPtr& pkt, AVFramePtr& frame)
{
	//return false;

	int gotPicture = 0;
	int err = avcodec_decode_video2(m_codecCtx, frame.get(), &gotPicture, pkt.get());
	return (gotPicture > 0);
}

void CVideoDecoder::flush()
{
}



} /* namespace av */
